package com.jams.goodox.activity.qa.teacher;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.util.Log;
import android.view.View;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * TA的回答，
 */
public class TeacherAnswerListActivity extends BaseActivity  implements
        OnItemClickListener, LFRecyclerView.LFRecyclerViewListener,
        LFRecyclerView.LFRecyclerViewScrollChange{


    private static final String TAG = TeacherAnswerListActivity.class.getSimpleName();
    @Bind(R.id.recycleView)
    LFRecyclerView recyclerView;


    private CommonRecycleViewAdapter pAdapter;
    private List<Question> list = new ArrayList<>();

    private boolean status = false;//判断加载成功还是失败
    private boolean isRefresh = true;

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            if (msg.what == 1) {
                if (isRefresh) {
                    recyclerView.stopRefresh(status);
                    pAdapter.notifyDataSetChanged();
                } else {
                    recyclerView.stopLoadMore();
                    pAdapter.notifyDataSetChanged();
                }
            }
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.qa_list_activity;
    }

    @Override
    protected void init() {

        recyclerView.setLoadMore(false);
        recyclerView.setRefresh(true);
        recyclerView.setNoDateShow();
        recyclerView.setAutoLoadMore(false);
        recyclerView.setOnItemClickListener(this);
        recyclerView.setLFRecyclerViewListener(this);
        recyclerView.setScrollChangeListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        pAdapter = new CommonRecycleViewAdapter(recyclerView, list, R.layout.wendajx_item) {
            @Override
            public void bindConvert(LFRecyclerViewHolder holder, int position, Object item, boolean isScrolling) {

                Question jxQuestion = (Question) item;
                holder.setText(R.id.nickname, jxQuestion.getNickName());
                holder.setText(R.id.time, TimeUtils.getDateToString(jxQuestion.getCreateTime()));
                holder.setText(R.id.descr,jxQuestion.getDescr());
                holder.loadImage(R.id.image, jxQuestion.getImgPath());

                if(jxQuestion.getQueState() == 0){
                    holder.setText(R.id.status,"未回答");
                }else {
                    holder.setText(R.id.status,"已回答");
                }
            }

        };

        recyclerView.setFootText("");

        recyclerView.setAdapter(pAdapter);

        requestData();
    }


    public void requestData() {
        clearMap();

        params.put("requestData", "{memberId:" + SePref.getId() + "}");

        String strEntity = gson.toJson(params);

        Log.d(TAG, " data strEntity= " + strEntity);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);

        Call<ResponseBody> example = createCallService(LoginService.class).own(body);

        showLoading();
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, " data questionChoice= " + data);
                    JSONObject jsonObject = new JSONObject(data);

                    if (200 == jsonObject.getInt("code")) {
                        status = true;
                        if (isRefresh) {
                            list.clear();
                        }
                        String responseData = jsonObject.getString("responseData");
                        JSONArray jsonArray = new JSONArray(responseData);
                        if (null == jsonArray || jsonArray.length() <= 0) {
                            //ToastUtil.show("没有更多数据");
                            handler.sendEmptyMessage(1);
                            return;
                        }

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            Question question = new Question();
                            question.setImgPath(object.getString("imgPath"));
                            question.setId(object.getInt("id"));
                            question.setQueState(object.getInt("queState"));
                            question.setNickName(object.getString("nickName"));
                            question.setDescr(object.getString("descr"));
                            question.setCreateTime(object.getLong("createTime"));

                            list.add(question);
                            Log.d(TAG, "question = " + question.toString());
                        }

                        pAdapter.notifyDataSetChanged();

                    } else {
                        ToastUtil.show("网络异常！");
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

                handler.sendEmptyMessage(1);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                status = false;
                handler.sendEmptyMessage(1);
                Log.d(TAG, "onFailure = " + t.getMessage());
            }
        });

    }


    @Override
    public void onRecyclerViewScrollChange(View view, int i, int i1) {

    }

    @Override
    public void onRefresh() {
        requestData();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onLongClick(int po) {

    }
}
